//
//  TMWechatSocietyManger.m
//  GoldChampion
//
//  Created by Mac on 2018/5/8.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "TMWechatSocietyManger.h"

@interface TMWechatSocietyManger()
@property(nonatomic, copy) TMWeChatSocietyLoginHandle                     loginHandle;/**< 登录回调 */
@property(nonatomic, copy) TMWeChatSocietyUserInfoHandle                     userHandle;/**< 用户信息回调 */

@property(nonatomic, copy) TMWeChatSocietyLoginHandle                     shareHandle;/**< 分享 */
@property(nonatomic, copy) TMWeChartMangerPayHandle                     payHandle;/**< 支付回调 */
@end
@implementation TMWechatSocietyManger
+ (TMWechatSocietyManger *)manger{
    static TMWechatSocietyManger * manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = TMWechatSocietyManger.new;
    });
    return manger;
}
- (BOOL)registerWechatWithAppId:(NSString *)appId{
    _appId = appId;
    bool success =  [WXApi registerApp:appId];
    return success;
}
- (void)beginLoginWithLoginHandle:(TMWeChatSocietyLoginHandle)handle{
    //微信登录
    //构造SendAuthReq结构体
    self.loginHandle = handle;
    SendAuthReq* req = [[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"snsapi_userinfo" ;
    [WXApi sendReq:req];
}
- (void)fetchUserInfoWithHandle:(TMWeChatSocietyUserInfoHandle)handle{
    self.userHandle = handle;
    if (self.appSecert.length && self.appId.length && self.token.length) {
         [self beginUserInfoNetWork];
    }else{
        NSLog(@"查询微信用户信息失败,appId appSecert token 存在空值");
    }
   
}
- (void)shareToWeChatText:(NSString *)text toFriendCirle:(BOOL)toFriendCirle handle:(TMWeChatSocietyShareHandle)handle{
    
     self.shareHandle = handle;
     NSString *kLinkURL = text;
     NSString *kLinkTitle = @"金冠";
     NSString *kLinkDescription = @"快来看看这个视频吧";
    
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    // 是否是文档
    req1.bText = NO; // WXSceneSession = 0,
    /**< 聊天界面 */ // WXSceneTimeline = 1, /**< 朋友圈 */ // WXSceneFavorite = 2,
    req1.scene = WXSceneSession;
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = kLinkTitle;
    //分享标题
    urlMessage.description = kLinkDescription;
    //分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logo"]];
    //分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = kLinkURL;
    //分享链接
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    //发送分享信息
    if (toFriendCirle) {
        req1.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req1];

}
- (void)startPayOrderDic:(NSDictionary *)orderDic payHandle:(TMWeChartMangerPayHandle)payHandle{
    self.payHandle = payHandle;
    NSDictionary * dataDic = orderDic;
    PayReq *request = [PayReq new];
    request.nonceStr = dataDic[@"noncestr"];
    request.package = dataDic[@"package"];
    request.partnerId = dataDic[@"partnerid"];
    request.prepayId = dataDic[@"prepayid"];
    request.sign = dataDic[@"sign"];
    request.timeStamp = [dataDic[@"timestamp"] intValue];
    [WXApi sendReq:request];
}
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSString * aleart;
        BOOL success = NO;
        if (loginresp.errCode == -2) {
            aleart =  @"您取消了微信登录";
        }
        if (loginresp.errCode == -4) {
            aleart =  @"您拒绝微信登录";
        }
        if (loginresp.errCode == 0) {
            aleart =  @"微信分享登录";
            success = YES;
            // 持有token
            self.token = token;
        }
        if (self.loginHandle) {
            self.loginHandle(success,aleart );
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        NSString * aleart;
        BOOL success = NO;
        if (share.errCode == -2) {
            aleart =  @"您取消了微信分享";
        }
        if (share.errCode == -4) {
            aleart =  @"您拒绝微信分享";
        }
        if (share.errCode == 0) {
            aleart =  @"微信分享成功";
            success = YES;
        }
        if (self.shareHandle) {
            self.shareHandle(success,aleart );
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        NSString * aleart;
        BOOL success = NO;
        if (pay.errCode == -2) {
            aleart =  @"您取消了微信支付";
        }
        if (pay.errCode == -4) {
             aleart =  @"您拒绝微信支付";
        }
        if (pay.errCode == 0) {
             aleart =  @"微信支付成功";
            success = YES;
        }
        if (self.payHandle) {
            self.payHandle(success,aleart );
        }
    }
}
- (void)beginUserInfoNetWork{
    
    NSString * url =   [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",self.appId,self.appSecert,self.token];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        if ([dic.allKeys containsObject:@"openid"]) {
            NSString * openid = [dic[@"openid"] description];
            NSString * acceesstoken = dic[@"access_token"];
            self.openid = openid;
            NSString * url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",acceesstoken,openid];
            [self sendUserInfoWithUrl:url];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.userHandle) {
            self.userHandle(nil, error.description);
        }
    }];
}
- (void)sendUserInfoWithUrl:(NSString*)url{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        if ([dic.allKeys containsObject:@"openid"]) {
            
            NSString * openid = dic[@"openid"];
            NSString * unionid = dic[@"unionid"];
            NSString * nickName = dic[@"nickname"];
            NSString * headimgurl = dic[@"headimgurl"];
            if (self.userHandle) {
                self.userHandle(dic, @"");
            }
            
        }else{
            if (self.userHandle) {
                self.userHandle(dic, @"没有OpenID");
            }
        }
        self.userHandle = nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.userHandle) {
            self.userHandle(nil, error.description);
        }
    }];
}
@end
